package com.hudilao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hudilao.common.R;
import com.hudilao.dto.CustomerMembershipDTO;
import com.hudilao.dto.MembershipRegisterLoginDTO;
import com.hudilao.entity.Customer;
import com.hudilao.entity.CustomerMembership;
import com.hudilao.exception.RegisterFailException;
import com.hudilao.mapper.CustomerMapper;
import com.hudilao.mapper.CustomerMembershipMapper;
import com.hudilao.service.CustomerMembershipService;
import com.sun.deploy.association.RegisterFailedException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CustomerMembershipServiceImpl extends ServiceImpl<CustomerMembershipMapper, CustomerMembership> implements CustomerMembershipService {

    @Autowired
    private CustomerMembershipMapper customerMembershipMapper;



    @Autowired
    private CustomerMapper customerMapper;

     public void updateCustomerBalance(long id, BigDecimal balance){
        customerMembershipMapper.updateBalanceById(id,balance);
    }

    @Override
    public R<String> register(MembershipRegisterLoginDTO membershipRegisterLoginDTO, long customerId) {
         //获取当前顾客
        LambdaQueryWrapper<CustomerMembership> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerMembership::getCustomerId,customerId);
        CustomerMembership customerMembershipOne = this.getOne(queryWrapper);

        //已注册过会员则不能再注册
        if(customerMembershipOne != null){
            return R.error("该用户已注册过会员");
        }

        //判断改昵称是否已被使用
        if(StringUtils.isNotBlank(membershipRegisterLoginDTO.getName())){
            CustomerMembership customerMembership = this.lambdaQuery()
                    .eq(CustomerMembership::getName,membershipRegisterLoginDTO.getName())
                    .one();
            if(customerMembership != null){
                return R.error("该昵称已被占用");
            }
        }

        //对密码进行加密
        membershipRegisterLoginDTO.setPassword(DigestUtils.md5DigestAsHex(membershipRegisterLoginDTO.getPassword().getBytes()));


        //保存当前用户数据信息
        CustomerMembership currentCustomerMembership = new CustomerMembership();
        currentCustomerMembership.setCustomerId(customerId);
        currentCustomerMembership.setName(membershipRegisterLoginDTO.getName());
        currentCustomerMembership.setPassword(membershipRegisterLoginDTO.getPassword());

        this.save(currentCustomerMembership);

        //会员注册
        return R.success("注册成功");
    }

    //管理端：会员分页查询
    @Override
    public Page<CustomerMembershipDTO> getMembers(int page, int pageSize, String name) {

        //构建分页查询page
        Page<CustomerMembershipDTO> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<CustomerMembership> queryWrapper = new LambdaQueryWrapper<>();

        //根据会员昵称查询
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(CustomerMembership::getName, name);
        }

        //queryWrapper.orderByDesc(CustomerMembership::getCreateTime);
        Page<CustomerMembership> membershipPage = this.page(new Page<>(page, pageSize), queryWrapper);

        List<CustomerMembershipDTO> dtoList = new ArrayList<>();

        for (CustomerMembership membership : membershipPage.getRecords()) {

            //根据customer_id筛选
            Customer customer = customerMapper.selectById(membership.getCustomerId());

            //查到customer的情况下
            if (customer != null) {
                CustomerMembershipDTO dto = new CustomerMembershipDTO();

                //对象拷贝
                BeanUtils.copyProperties(membership, dto);
                dto.setGender(customer.getGender());
                dto.setPhoneNumber(customer.getPhoneNumber());
                dto.setBirthdate(customer.getBirthdate());
                dtoList.add(dto);
            }
        }

        //返回分页对象
        pageInfo.setRecords(dtoList);
        pageInfo.setTotal(membershipPage.getTotal());
        return pageInfo;
    }

    //管理端：会员充值余额
    @Override
    public boolean updateBalance(Long memberId, BigDecimal amount) {

         //获取会员
        CustomerMembership member = customerMembershipMapper.selectById(memberId);

        //会员不为空的情况下增加余额
        if (member != null) {
            //增加余额
            member.setBalance(member.getBalance().add(amount));
            return customerMembershipMapper.updateById(member) == 1;
        }
        return false;
    }

    //管理端：会员扣除余额
    @Override
    public boolean decreaseBalance(Long memberId, BigDecimal amount) {

         //获取会员
        CustomerMembership member = customerMembershipMapper.selectById(memberId);

        //判断要比余额大才能扣除
        if (member != null && member.getBalance().compareTo(amount) >= 0) {
            //扣除金额
            member.setBalance(member.getBalance().subtract(amount));
            return customerMembershipMapper.updateById(member) == 1;
        }
        return false;
    }
}
